/*
 * MIT License
 *
 * Copyright (c) 2020 dybai
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <sys/types.h>
#include <sys/stat.h>

#include "settty.h"

volatile int quit_flag = 0;

void s_int(int s)
{
    if (SIGINT == s)
    {
        quit_flag = 1;
    }
}

int send_serial(int fd)
{
    char ch = '0';
    int pos = 0;

    for (pos = 0; !quit_flag; pos++)
    {
        if ((0 != pos) && (pos % 8 == 0))
        {
            printf("\n");
        }
        printf("%02X %c ", ch, ch);
        fflush(stdout);
        if (write(fd, &ch, 1) < 0)
        {
            if (EINTR == errno)
            {
                return 0;
            }
            return errno;
        }
        switch (ch)
        {
            case '9':
                ch = 'A';
                break;
            case 'Z':
                ch = 'a';
                break;
            case 'z':
                ch = '0';
                break;
            default:
                ch++;
                break;
        }
        sleep(1);
    }

    return 0;
}

int main(int argc, char *argv[])
{
    int ret = 0;
    int fd = -1;
    struct sigaction action;
    action.sa_handler = s_int;
    action.sa_flags = 0;

    sigaction(SIGINT, &action, NULL);

    settty(PATH_TTY);

    fd = open(PATH_TTY, O_WRONLY);
    if (fd < 0)
    {
        perror("Open ttyUSB0");
        ret = errno;
        goto e_open;
    }

    if ((ret = send_serial(fd)))
    {
        fprintf(stderr, "ERROR: Call dump() failed: %s\n", strerror(ret));
        goto e_dump;
    }

    printf("Done.\n");

e_dump:
    close(fd);
e_open:
    return ret;
}
